package com.good.child.ui.activity.constants.update;

import android.annotation.SuppressLint;
import android.app.DownloadManager;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.database.Cursor;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.os.SystemClock;

import com.blankj.utilcode.util.ThreadUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.good.child.R;
import com.good.child.ui.utils.CalcUtils;

import java.io.File;
import java.util.concurrent.TimeUnit;

/**
 * Create on: 2024/8/4
 * by Mr.Zhu
 * Description: TODO
 */
public class DownloadUtils extends IUpdateDownload {
    //下载器
    private DownloadManager downloadManager;
    private Context mContext;
    //下载的ID
    private long downloadId;
    private File file;

    public DownloadUtils(Context context, String url, String name, DownloadCallback callback) {
        super(callback);
        this.mContext = context.getApplicationContext();
        startListener();
        downloadAPK(url, name);
    }

    //下载apk
    private void downloadAPK(String url, String name) {
        //创建下载任务
        DownloadManager.Request request = new DownloadManager.Request(Uri.parse(url));
        //在通知栏中显示，默认就是显示的
        request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE);
        request.setAllowedNetworkTypes(DownloadManager.Request.NETWORK_WIFI|DownloadManager.Request.NETWORK_MOBILE);
        String appName = mContext.getString(R.string.app_name);
        request.setTitle(appName + "版本更新");
        request.setDescription("新版" + appName + "下载中...");
        request.setVisibleInDownloadsUi(true);
        //设置下载的路径
        file = new File(mContext.getExternalFilesDir(Environment.DIRECTORY_DOWNLOADS), name);
        if (file.exists()) {
            file.delete();
        }
        request.setDestinationUri(Uri.fromFile(file));
        //获取DownloadManager
        if (downloadManager == null)
            downloadManager = (DownloadManager) mContext.getSystemService(Context.DOWNLOAD_SERVICE);
        //将下载请求加入下载队列，加入下载队列后会给该任务返回一个long型的id，通过该id可以取消任务，重启任务、获取下载的文件等等
        if (downloadManager != null) {
            downloadId = downloadManager.enqueue(request);
        }
        //注册广播接收者，监听下载状态
        IntentFilter filter = new IntentFilter(DownloadManager.ACTION_DOWNLOAD_COMPLETE);
        if (receiver == null) {
            receiver = new BroadcastReceiver() {
                @Override
                public void onReceive(Context context, Intent intent) {
                    checkStatus();
                }
            };
            mContext.getApplicationContext().registerReceiver(receiver, filter);
        }
    }

    //广播监听下载的各个状态
    private static BroadcastReceiver receiver;

    private int downloadPercent;

    //检查下载状态
    private void checkStatus() {
        DownloadManager.Query query = new DownloadManager.Query();
        //通过下载的id查找
        query.setFilterById(downloadId);
        Cursor cursor = downloadManager.query(query);
        if (cursor==null){
            return;
        }
        try {
            if (cursor.moveToFirst()) {
                @SuppressLint("Range") int status = cursor.getInt(cursor.getColumnIndex(DownloadManager.COLUMN_STATUS));
                switch (status) {
                    //正在下载
                    case DownloadManager.STATUS_RUNNING:
                        int percent = getDownloadPercent(cursor);
                        if (downloadPercent != 0 && downloadPercent == percent)
                            return;
                        downloadPercent = percent;
                        if (getCallback() != null) {
                            getCallback().onDownloading(downloadPercent);
                        }
                        break;
                    //下载完成
                    case DownloadManager.STATUS_SUCCESSFUL:
                        stopQuery();
                        unregisterBroadcast();
                        if (getCallback() != null) {
                            getCallback().onDownloading(100);
                            SystemClock.sleep(800);
                        }
                        //下载完成安装APK
                        installAPK();
                        break;
                    //下载失败
                    case DownloadManager.STATUS_FAILED:
                        if (getCallback() != null) {
                            stopQuery();
                            unregisterBroadcast();
                            getCallback().onDownloadFail();
                        }else{
                            ToastUtils.showShort("网络异常，更新失败");
                        }
                        break;
                }
            }
        }finally {
            cursor.close();
        }
    }

    private void unregisterBroadcast() {
        if (receiver != null) {
            try {
                mContext.getApplicationContext().unregisterReceiver(receiver);
            } catch (Exception e) {
            }
            receiver = null;
        }
    }

    private void installAPK() {
        Intent intent = new Intent(Intent.ACTION_VIEW);
        // 由于没有在Activity环境下启动Activity,设置下面的标签
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        //Android 7.0以上要使用FileProvider
        if (Build.VERSION.SDK_INT >= 24) {
            //参数1 上下文, 参数2 Provider主机地址 和配置文件中保持一致   参数3  共享的文件
            Uri apkUri = fileprovider.getUriForFile(mContext,
                    mContext.getPackageName() + ".fileProvider", file);
            //添加这一句表示对目标应用临时授权该Uri所代表的文件
            intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
//            intent.addFlags(Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
            intent.setDataAndType(apkUri, "application/vnd.android.package-archive");
        } else {
            intent.setDataAndType(Uri.fromFile(file),
                    "application/vnd.android.package-archive");
        }
        mContext.startActivity(intent);
    }

    /**
     * 如果下载完成，没有安装，重新发起安装请求
     */
    public void reInstall() {
        checkStatus();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        stopQuery();
    }


    /**
     * 注册ContentObserver
     */
    void startListener() {
        mQueryProgressRunnable = new QueryRunnable();
        ThreadUtils.executeByCachedAtFixRate(mQueryProgressRunnable, 100, 50, TimeUnit.MILLISECONDS);
    }

    private QueryRunnable mQueryProgressRunnable;

    //查询下载进度
    private class QueryRunnable extends ThreadUtils.SimpleTask<Void> {
        @Override
        public Void doInBackground() throws Throwable {
            checkStatus();
            return null;
        }

        @Override
        public void onSuccess(Void result) {

        }
    }

    //查询下载进度
    private synchronized int getDownloadPercent(Cursor c) {
        @SuppressLint("Range") long downloadSoFar = c.getLong(c.getColumnIndex(DownloadManager.COLUMN_BYTES_DOWNLOADED_SO_FAR));
        @SuppressLint("Range") long downloadAll = c.getLong(c.getColumnIndex(DownloadManager.COLUMN_TOTAL_SIZE_BYTES));
        if (downloadSoFar > 0 && downloadAll > 0) {
            double present = CalcUtils.div(downloadSoFar + "", downloadAll + "");
            return (int) (present * 100);
        }
        return 0;
    }

    //停止查询下载进度
    private void stopQuery() {
        if (mQueryProgressRunnable != null) {
            ThreadUtils.cancel(mQueryProgressRunnable);
            mQueryProgressRunnable = null;
        }
    }

}
